const express = require('express')
const router = express.Router()
const Category = require('../../models/Category')

let responseData = {
	resultCode: 0,
	resultMsg: 'success',
	data: {}
}


/** 后台查询标签列表接口 /category
 * 
 */
router.get('/', function(req, res, next) {
	Category.find().then(function(categoryList) {
		responseData.data['list'] = categoryList
		responseData.resultCode = 0
		responseData.resultMsg = 'success'
		res.json(responseData)
		return
	})
})

/** 后台添加标签接口 /category/add
 * 
 */
router.post('/add', function(req, res, next) {
	let categoryName = req.body.categoryName
	let category = new Category({
		categoryName: categoryName
	})
	Category.findOne({
		categoryName: categoryName
	}).then(function(categoryInfo) {
		if(categoryInfo) {
			responseData.resultCode = 1
			responseData.resultMsg = '标签名已存在'
			res.json(responseData)
			return
		}

		category.save().then(function(categoryInfo) {
			res.json(responseData)
		})
		
	})
})


/** 后台更新标签接口 /category/update
 * 需要数据： id  categoryName
 */
router.post('/update', function(req, res) {
	let categoryName = req.body.categoryName
	let id = req.body.id
	Category.findOne({
		categoryName: categoryName
	}).then(function(categoryInfo) {
		if(categoryInfo) {
			responseData.resultCode = 1
			responseData.resultMsg = '标签名已存在'
			res.json(responseData)
		}

		Category.update({
			_id: id
		}, {
			categoryName: categoryName
		}).then(function(affectLine) {
			res.json(responseData)
		})
		
	})
})

/** 后台删除标签接口 /category/delete
 *  需要数据： id 
 */
router.get('/delete', function(req, res){
	let id = req.query.id
	Category.findOne({
		_id: id
	}).then(function(categoryInfo) {
		if(!categoryInfo) {
			responseData.resultCode = 1
			responseData.resultMsg = '标签不存在'
			res.json(responseData)
		}
		Category.remove({
			_id: id
		}).then(function(affectLine) {
			res.json(responseData)
		})
	})
})


module.exports = router